package com.aixingfu.sports;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.aixingfu.sports.MVP.contract.RetrievePwdContract;
import com.aixingfu.sports.MVP.contract.UserInfoContract;
import com.aixingfu.sports.MVP.presenter.RetrievePwdPresenter;
import com.aixingfu.sports.MVP.presenter.UserInfoPresenter;
import com.aixingfu.sports.Model.CodeModel;
import com.aixingfu.sports.Model.RetrievePwdModel;
import com.aixingfu.sports.Model.UserInfoModel;
import com.aixingfu.sports.ui.activity.IdentityVerificationActivity;
import com.aixingfu.sports.view.IDCardInfoExtractor;
import com.aixingfu.sports.view.PopupWindowCheckChoose;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.CountDownTimerUtils;
import com.orie.librarybase.utils.UserUtils;
import com.vondear.rxtool.RxRegTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//基本信息
@Route(path = "/main/ElectronicContractActivity")
public class ElectronicContractActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, RetrievePwdContract.MyView, UserInfoContract.MyView {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_main)
    TextView tvMain;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.ed_guardian_name)
    EditText edGuardianName;
    @BindView(R.id.ll_certificates)
    LinearLayout llCertificates;
    @BindView(R.id.ed_certificate_code)
    EditText edCertificateCode;
    @BindView(R.id.ed_birthday)
    EditText edBirthday;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.ed_code)
    EditText edCode;
    @BindView(R.id.radio)
    RadioGroup radio;
    @BindView(R.id.radio_btn_man)
    RadioButton radioBtnMan;
    @BindView(R.id.radio_btn_woman)
    RadioButton radioBtnWoman;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.tv_card_type)
    TextView tvCardType;
    private RetrievePwdPresenter retrievePwdPresenter;
    private UserInfoPresenter userInfoPresenter;
    private String codedata;
    private String sexNum = "1";
    private PopupWindowCheckChoose mPopup;
    private ArrayList<String> mList = new ArrayList();
    private String userType="";
    private CountDownTimerUtils countDownTimerUtils;
    private String birthDay;
    private String userName = "";
    private String mobile = "";
    private String sex = "";
    private String cardtype = "";
    private String idCard = "";
    private String type = "";
    private String member_id = "";
    private String birth_data = "";
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_electronic_contract;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/ElectronicContractActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        try {
            Bundle bundle = getIntent().getExtras();
            userName = bundle.getString("userName", "");
            sex = bundle.getString("sex", "");
            mobile = bundle.getString("mobile", "");
            cardtype = bundle.getString("cardtype", "");
            idCard = bundle.getString("idCard", "");
            type = bundle.getString("type", "");
            member_id = bundle.getString("member_id", "");
            birth_data = bundle.getString("birth_data", "");
            retrievePwdPresenter = new RetrievePwdPresenter();
            retrievePwdPresenter.attachView(this);
            userInfoPresenter = new UserInfoPresenter();
            userInfoPresenter.attachView(this);
            mList=getPopList();
            mPopup = new PopupWindowCheckChoose(ElectronicContractActivity.this, mList);
            mPopup.setTagTxt("请选择证件类型")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            mPopup.setOnEventLisenter(positionList -> {
                mPopup.dismiss();
                tvCardType.setText(mList.get(positionList.get(0)));
                userType = mList.get(positionList.get(0));
            });
            edBirthday.setOnFocusChangeListener(new android.view.View.
                    OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        // 此处为得到焦点时的处理内容
                        if ("身份证".equals(userType)){
                            if (RxRegTool.validateIdCard(edCertificateCode.getText().toString())){
                                //拿到身份证号码文本
                                IDCardInfoExtractor idCardInfo = new IDCardInfoExtractor(edCertificateCode.getText().toString().trim());
                                //从身份证号码中提取出生日期
                                birthDay = idCardInfo.getYear() + "-" + idCardInfo.getMonth() + "-" + idCardInfo.getDay();
                                edBirthday.setText(birthDay);
                            }else {
                                edBirthday.setText("");
                            }

                        }
                    } else {
                        // 此处为失去焦点时的处理内容
                    }
                }
            });
            edName.setText(userName);
            if ("1".equals(sex)){
                radio.check(R.id.radio_btn_man);
                sexNum = "1";
            }else if ("2".equals(sex)){
                radio.check(R.id.radio_btn_woman);
                sexNum = "2";
            }
            if ("1".equals(cardtype)){
                tvCardType.setText("身份证");
                userType="身份证";
            }else if ("2".equals(cardtype)){
                tvCardType.setText("居住证");
                userType="居住证";
            }else if ("3".equals(cardtype)){
                tvCardType.setText("签证");
                userType="签证";
            }else if ("4".equals(cardtype)){
                tvCardType.setText("护照");
                userType="护照";
            }else if ("5".equals(cardtype)){
                tvCardType.setText("户口本");
                userType="户口本";
            }else if ("6".equals(cardtype)){
                tvCardType.setText("军人证");
                userType="军人证";
            }
            edCertificateCode.setText(idCard);
            if ("1".equals(type)){
                edPhone.setText(mobile);
                edPhone.setEnabled(false);
                tvMain.setText("上一页");
            }else {
                tvMain.setText("回首页");
            }
            edBirthday.setText(birth_data);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 数据
     *
     * @return
     */
    public ArrayList<String> getPopList() {
        ArrayList<String> popList = new ArrayList<>();
        popList.add("身份证");
        popList.add("居住证");
        popList.add("签证");
        popList.add("护照");
        popList.add("户口本");
        popList.add("军人证");
        return popList;
    }
    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        radio.setOnCheckedChangeListener(this);
    }

    @OnClick({R.id.tv_main, R.id.ll_certificates, R.id.tv_next, R.id.tv_getcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_main:
                hideIputKeyboard();
                finish();
                break;
            case R.id.tv_getcode:
                String phone = edPhone.getText().toString();
                if (TextUtils.isEmpty(phone)){
                    RxToast.normal(ElectronicContractActivity.this,"请输入手机号").show();
                }else {
                    countDownTimerUtils = new CountDownTimerUtils(ElectronicContractActivity.this, tvGetcode, 60000, 1000);
                    countDownTimerUtils.start();
                    getCode(phone);
                }

                break;
            case R.id.ll_certificates:
                hideIputKeyboard();
                mPopup.showPop(tvCardType);
                break;
            case R.id.tv_next:
                String name = edName.getText().toString();
                String guardianName = edGuardianName.getText().toString();
                String cardType = tvCardType.getText().toString();
                String certuficateCode = edCertificateCode.getText().toString();
                birthDay = edBirthday.getText().toString();
                String  mobile= edPhone.getText().toString();
                String code = edCode.getText().toString();
                if (TextUtils.isEmpty(name)){
                    RxToast.normal(ElectronicContractActivity.this,"请输入姓名").show();
                }else if (TextUtils.isEmpty(cardType)){
                    RxToast.normal(ElectronicContractActivity.this,"请选择证件类型").show();
                }else if (TextUtils.isEmpty(certuficateCode)){
                    RxToast.normal(ElectronicContractActivity.this,"请输入证件号").show();
                }else if (TextUtils.isEmpty(mobile)){
                    RxToast.normal(ElectronicContractActivity.this,"请输入手机号").show();
                }else if (TextUtils.isEmpty(code)){
                    RxToast.normal(ElectronicContractActivity.this,"请输入验证码").show();
                }else if ("身份证".equals(userType)){
                    if (!RxRegTool.isIDCard(certuficateCode)){
                        RxToast.normal(ElectronicContractActivity.this,"请输入正确的身份证号").show();
                    }else {
                        getUserInfo(name,guardianName,cardType,certuficateCode,birthDay,mobile,code);
                    }
                }else {
                    getUserInfo(name,guardianName,cardType,certuficateCode,birthDay,mobile,code);
                }
//                IdentityVerificationActivity.startActivityByRoute();
                break;
        }
    }
    public void getCode(String accountNumber) {
        if (retrievePwdPresenter.isViewAttached()) {
            String companyID = UserUtils.getCompanyID(ElectronicContractActivity.this);
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", accountNumber);
            map.put("company_id", companyID);
            if ("1".equals(type)){
                map.put("type", "member");
            }else {
                map.put("type", "");
            }
            retrievePwdPresenter.getCode(map);
        }
    }
    public void getUserInfo(String name,String guardianName,String cardType,String certuficateCode,String birthday,String mobile,String code) {
        if (userInfoPresenter.isViewAttached()) {
            String companyID = UserUtils.getCompanyID(ElectronicContractActivity.this);
            HashMap<String, String> map = new HashMap<>();
            map.put("user_name", name);
            map.put("guardian_people", guardianName);
            map.put("user_sex", sexNum);
            if ("身份证".equals(userType)){
                map.put("user_paper", "1");
            }else if ("居住证".equals(userType)){
                map.put("user_paper", "2");
            }else if ("签证".equals(userType)){
                map.put("user_paper", "3");
            }else if ("护照".equals(userType)){
                map.put("user_paper", "4");
            }else if ("户口本".equals(userType)){
                map.put("user_paper", "5");
            }else if ("军人证".equals(userType)){
                map.put("user_paper", "6");
            }
            map.put("user_paper_num", certuficateCode);
            map.put("user_birth", birthday);
            map.put("user_mobile", mobile);
            map.put("code", code);
            map.put("company_id", companyID);
            if ("1".equals(type)){
                map.put("type", "member");
            }else {
                map.put("type", "");
            }
            userInfoPresenter.getUserInfo(map);
        }
    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            //男
            case R.id.radio_btn_man:
                //男
                sexNum = "1";
                break;
            //女
            case R.id.radio_btn_woman:
                //女
                sexNum = "2";
                break;
        }
    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setUserInfo(UserInfoModel data) {
        if (data.getCode() == 1){
            RxToast.normal(ElectronicContractActivity.this,data.getMessage()).show();
            ARouter.getInstance().build("/main/IdentityVerificationActivity").withString("type",type).withString("member_id",member_id).navigation();
        }else {
            RxToast.normal(ElectronicContractActivity.this,data.getMessage()).show();
        }
    }

    @Override
    public void setCode(CodeModel data) {
        if (data.getCode() == 1) {
            codedata = String.valueOf(data.getData());
            edCode.setText(codedata);
        } else {
            RxToast.normal(ElectronicContractActivity.this, data.getMessage()).show();
        }

    }

    @Override
    public void setRetievePwd(RetrievePwdModel data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {
    }
    @Override
    public Context getMyContext() {
        return this;
    }
    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }
}
